//
//  LoginViewController.swift
//  手账
//
//  Created by zhuxiaoxiang on 2018/12/12.
//  Copyright © 2018年 zhuxiaoxiang. All rights reserved.
//

import UIKit

class LoginViewController: BaseViewController {
    
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var verifyCodeTF: UITextField!
    @IBOutlet weak var verifyCodeBtn: UIButton!
    @IBOutlet weak var agreementLB: UILabel!
    @IBOutlet weak var agreementTV: UITextView!
    @IBOutlet weak var picCodeTF: UITextField!
    @IBOutlet weak var codeView: CodeView!
    @IBOutlet weak var loginBtn: UIButton!
    
    fileprivate var time = 60
    
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func config() {
        super.config()
        let text = agreementTV.text
        let attributedString = NSMutableAttributedString(attributedString: agreementTV.attributedText)
        attributedString.addAttributes([NSAttributedStringKey.foregroundColor: kBaseBlueColor,NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.link: "agreement://"], range: NSRange(location: text!.count - 10, length: 10))
        agreementTV.attributedText = attributedString
        self.verifyCodeBtn.layer.cornerRadius = 5
        self.verifyCodeBtn.layer.masksToBounds = true
        self.verifyCodeBtn.backgroundColor = kBaseGrayColor
        kNotificationCenter.addObserver(self, selector: #selector(textFieldDidChangeValue), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }

}

extension LoginViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
}

extension LoginViewController {
    @IBAction func login(_ sender: UIButton) {
        let phone = phoneTF.text!
        let picCodeText = picCodeTF.text!
        let verifyCode = verifyCodeTF.text!
        if picCodeText.lowercased() == codeView.changeString!.lowercased() {
            BmobSMS.verifySMSCodeInBackground(withPhoneNumber: phone, andSMSCode: verifyCode, resultBlock: { (isSuccess, error) in
                if isSuccess == true {
                    AppUser.sharedInstance.login(phone)
                    self.showMessage("登录成功")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                        self.dismiss(animated: true, completion: nil)
                    })
                }else {
                    self.showMessage("短信验证码输入不正确")
                }
            })
        }else {
            self.showMessage("图片验证码输入不正确")
            codeView.updateCode()
        }
    }
    
    @IBAction func getVerifyCode(_ sender: UIButton) {
        let text = phoneTF.text!
        if text.count == 0 {
            self.showMessage("请输入手机号")
        }else {
            XXHUD.sharedInstance.showLoading(self.view)
            if text.judgeIfMobileCode() {
                BmobSMS.requestCodeInBackground(withPhoneNumber: text, andTemplate: "小明记账", resultBlock: { [weak self] (code, error) in
                    XXHUD.sharedInstance.hide((self?.view)!)
                    if error == nil {
                        self?.verifyCodeBtn.isEnabled = false
                        self?.showMessage("短信验证码已发送")
                        self?.time = 60
                        if #available(iOS 10.0, *) {
                            self?.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
                                self?.verifycodeRemainingTime()
                            })
                        } else {
                            // Fallback on earlier versions
                            self?.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self?.verifycodeRemainingTime), userInfo: nil, repeats: true)
                        }
                    }else {
                        self?.showMessage("短信验证码请求失败，请稍后重试")
                    }
                })
            }else {
                XXHUD.sharedInstance.hide(self.view)
                self.showMessage("手机号输入不正确")
            }
        }
    }
    
    @objc func verifycodeRemainingTime() {
        if time == 0 {
            self.timer?.invalidate()
            self.timer = nil
            self.enableButton(self.verifyCodeBtn, isEnable: true)
            self.verifyCodeBtn.setTitle("获取验证码", for: .normal)
            self.verifyCodeBtn.setTitle("获取验证码", for: .disabled)
        }else {
            self.verifyCodeBtn.setTitle("\(time) s", for: .disabled)
            self.verifyCodeBtn.backgroundColor = kBaseGrayColor
        }
        time = time - 1
    }
}

extension LoginViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == self.phoneTF {
            return (textField.text?.count)! + string.count < 12
        }else if textField == self.picCodeTF {
            let textLen = (textField.text?.count)!
            if (textLen == 3 || textLen == 4) && (textField.text! + string).count == textLen + 1 {
                self.enableButton(self.verifyCodeBtn, isEnable: true)
            }else {
                self.enableButton(self.verifyCodeBtn, isEnable: false)
            }
            return (textField.text?.count)! + string.count < 5
        }else {
            return (textField.text?.count)! + string.count < 7
        }
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        let phone = phoneTF.text
        let verifyCode = verifyCodeTF.text
        let picCode = picCodeTF.text
        if (phone != nil && phone!.count == 11) && (verifyCode != nil && verifyCode!.count == 6) && (picCode != nil && picCode!.count == 4) {
            self.enableButton(self.verifyCodeBtn, isEnable: true)
            self.enableButton(self.loginBtn, isEnable: true)
        }else {
            self.enableButton(self.loginBtn, isEnable: false)
        }
        return true
    }
}

extension LoginViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if URL.scheme! == "agreement" {
            let webViewVC = BaseWebViewController()
            webViewVC.url = "https://xuxiaodai.wordpress.com/2018/12/24/%E5%B0%8F%E6%98%8E%E8%AE%B0%E8%B4%A6%E8%BD%AF%E4%BB%B6%E8%AE%B8%E5%8F%AF%E5%8F%8A%E6%9C%8D%E5%8A%A1%E5%8D%8F%E8%AE%AE/"
            self.navigationController?.pushViewController(webViewVC, animated: true)
            return false
        }
        return true
    }
    
    @objc func textFieldDidChangeValue() {
        let phone = phoneTF.text!
        let verifyCode = verifyCodeTF.text!
        let picCode = picCodeTF.text!
        if phone.count == 11 && verifyCode.count == 6 && picCode.count == 4 {
            self.enableButton(self.loginBtn, isEnable: true)
        }else {
            self.enableButton(self.loginBtn, isEnable: false)
        }
    }
}

extension LoginViewController {
    func enableButton(_ button: UIButton, isEnable: Bool) {
        button.isEnabled = isEnable
        button.backgroundColor = isEnable == true ? kBaseBlueColor : kBaseGrayColor
    }
}
